package com.kitty.game.task.service.taskHandler;

import com.kitty.common.model.Pos;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.service.seal.ShangGuBossHandler;
import com.kitty.game.activity.service.seal.WanNianBossHandler;
import com.kitty.game.base.service.BagService;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.config.GameMap;
import com.kitty.game.config.MapBossPos;
import com.kitty.game.config.TaskSet;
import com.kitty.game.enter.Position;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.i18n.I18nId;
import com.kitty.game.i18n.I18nIdDataPool;
import com.kitty.game.map.service.MapService;
import com.kitty.game.mount.message.RespSummonMountNotify;
import com.kitty.game.npc.message.RespAutoWalk;
import com.kitty.game.npc.message.RespStartGather;
import com.kitty.game.pet.PetDataPool;
import com.kitty.game.pet.bean.PetObject;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.role.model.Role;
import com.kitty.game.task.message.vo.TaskInfo;
import com.kitty.game.task.model.product.TaskType;
import com.kitty.game.task.service.message.AutoCangBaoTu;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.mina.message.MessagePusher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.text.MessageFormat;
import java.util.concurrent.ThreadLocalRandom;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**挖宝(普通藏宝图和超级藏宝图)*/
@Component
@Slf4j
public class DigTreasureTaskHandler extends TaskHandler {
    private final static int MIN_LEVEL = 40;
    /**挖宝(藏宝图)对应的任务ID*/
    public static final int DIG_TREASURE_TASKID_NORMAL = 114;
    /**挖宝(超级藏宝图)对应的任务ID*/
    public static final int DIG_TREASURE_TASKID_SUPER = 82;
    /**挖宝(特级藏宝图)对应的任务ID*/
    public static final int DIG_TREASURE_TASKID_SUPER_SENIOR = 140;

    private final static String LEVEL_NOT_ENOUGH = "以你现在的能力还无法知晓超级藏宝图的秘密#R（等级不足40级）#n。";
    private final static String ACCEPTED = "你已经知道一个宝藏的秘密了，不要太贪心哦。";

    private final static List<Integer> MAPIDS = Arrays.asList(2000, 3000, 4000, 24000, 6000, 8000, 9000, 8100, 13000, 14000, 15000, 16000, 10200, 10300, 10400, 10500, 16100, 18000, 17000, 17100,
            17200, 17400, 17500, 17600, 17700, 22000, 19002);

    //掉落 游戏币 首饰 变异 女娲石 上古
    private final static String wabaoDiaoLuoSenior = "money=5000,weijianding=2000,shoushi=300,shanggu=500,wannian=2000,bianyi=1";
    private final static String tejiwabaoMoney = "450=50,750=40,1000=30,3000=20,6000=10";
    private final static String wabaoMoneySenior = "20=80,40=60,60=50,100=35,200=15,400=10,600=5,1000=2,2000=1";
    private final static String wabaoDiaoLuo = "money=2000,shoushi=0,weijianding=800,bianyi=0,nvwashi=50,shanggu=800,wannian=100";
    private final static String wabaoMoney = "10=80,20=60,30=50,50=35,100=15,200=10,300=5,500=2,1000=1";
    private final static String wabaoMoneyNormal = "1=1,2=1,3=1,4=1,5=1,6=1,7=1,8=1,9=1,10=1";

    @Override
    public TaskType getTaskType() {
        return TaskType.DIG_TREASURE;
    }

    /**使用藏宝图(普通或者超级)道具*/
    public void useTreasureMapItem(Role role, byte treasureType, RoleEquip roleEquip) {
        /**检测能否使用*/
        String check = checkUse(role);
        if (check != null) {
            log.info("[TREASURE_TASK]|use|{}|{}|{}", treasureType, role.getUid(), check);
            MessagePusher.pushMessage(role, new RespMsg(check));
            return ;
        }

        int delCountSuc = SpringUtils.getEquipService().delEquipNum(role, roleEquip, 1);
        /**没有使用成功返回*/
        if (delCountSuc <= 0) {
            return ;
        }

        role.getActivity().setDigTreasureType(treasureType);
        /**接取任务*/
        acceptTask(role, treasureType);
    }



    /**检测能否使用藏宝图(普通或者超级)道具*/
    private String checkUse(Role role) {
        if (role.getLevel() < MIN_LEVEL) {
            return LEVEL_NOT_ENOUGH;
        }

        TaskSet taskSet = getTaskSetByType(role);
        if (taskSet != null) {
            return ACCEPTED;
        }

        return null;
    }

    /**接取挖宝任务*/
    private void acceptTask(Role role, byte treasureType) {
        int taskId = 0;
        if (treasureType == Const.DIG_TREASURE_TYPE_SUPER_SENIOR) {
            taskId = DIG_TREASURE_TASKID_SUPER_SENIOR;
        } else if (treasureType == Const.DIG_TREASURE_TYPE_SUPER) {
            taskId = DIG_TREASURE_TASKID_SUPER;
        } else {
            taskId = DIG_TREASURE_TASKID_NORMAL;
        }
        TaskSet taskSet = taskService.getTaskSet(taskId, role);
        acceptTask(role, taskSet);
    }

    @Override
    public void doBeforeAccept(Role role, TaskSet taskSet) {
        super.doBeforeAccept(role, taskSet);
        /**随机生成任务对应的一个目标位置*/
        randomTargetPosition(role);
    }

    @Override
    public void doAfterAccept(Role role, TaskSet taskSet) {
        super.doAfterAccept(role, taskSet);

        /**自动寻路到对应目标*/
        TaskInfo taskInfo = getTaskInfo(role, taskSet);
        RespAutoWalk respAutoWalk = new RespAutoWalk();
        respAutoWalk.setTaskName(taskInfo.getTaskName());
        respAutoWalk.setDest(taskInfo.getTaskZhiyin());
        MessagePusher.pushMessage(role, respAutoWalk);
        log.info("[TREASURE_TASK]|goto|{}|{}|{}|{}", role.getActivity().getDigTreasureType(), role.getUid(), taskSet.getId(), taskInfo.getTaskZhiyin());
    }

    /**随机生成挖宝的目标位置*/
    private void randomTargetPosition(Role role) {
        NewBossService bossService = SpringUtils.getBean(NewBossService.class);
        int mapId = getRandomMapId();
        MapBossPos mapBossPos = bossService.getMapBossPos(mapId);
        Position randomPosition = bossService.getRandomPosition(mapBossPos);
        Pos pos = new Pos(randomPosition.getX(), randomPosition.getY(), (byte)0, mapBossPos.getMapId());
        role.getActivity().setDigTreasurePosition(pos);
        log.info("[TREASURE_TASK]|randomposition|{}|{}|{}|{}|{}", role.getActivity().getDigTreasureType(), role.getUid(), pos.getMapId(), pos.getX(), pos.getY());
    }

    /**获得随机出现的地图ID*/
    private int getRandomMapId() {
        int index = ThreadLocalRandom.current().nextInt(MAPIDS.size());
        return MAPIDS.get(index);
    }

    @Override
    public TaskInfo getTaskInfo(Role role, TaskSet taskSet) {
        TaskInfo taskInfo = super.getTaskInfo(role, taskSet);
        Pos digTreasurePosition = role.getActivity().getDigTreasurePosition();
        if (digTreasurePosition != null) {
            GameMap gameMap = SpringUtils.getMapService().getMap(digTreasurePosition.getMapId());
            String zhiying = MessageFormat.format(taskInfo.getTaskZhiyin(),gameMap.getName(),gameMap.getName(),digTreasurePosition.getX(),digTreasurePosition.getY());
            taskInfo.setTaskZhiyin(zhiying);
        }
        return taskInfo;
    }

    /**检测是否开始挖宝(是否走到目标位置)*/
    public boolean checkStartDig(Role role, TaskSet taskSet) {
        if (taskSet.getTaskType() != getTaskType()) {return false;}
        if (taskService.isTaskAccepted(role, taskSet) == false) {return false;}
        int endtime = role.getTempCache("dig_treasure_end_time", 0);
        if(endtime>0){
            return false;
        }
        /**玩家正在对话或者战斗过程中不能触发*/
        if (role.getTalk().isInTalk()
                || SpringUtils.getFightService().isInFight(role)) {
            log.info("[TREASURE_TASK]|checkStartDig|{}|{}|{}|{}|{}", role.getActivity().getDigTreasureType(), role.getUid(), taskSet.getId(), role.getTalk().isInTalk(), SpringUtils.getFightService().isInFight(role));
            return false;
        }
        Pos digTreasurePosition = role.getActivity().getDigTreasurePosition();
        if (digTreasurePosition == null) {
            log.info("[TREASURE_TASK]|checkStartDig|{}|{}|{}|{}", role.getActivity().getDigTreasureType(), role.getUid(), taskSet.getId(), "position is null");
            return false;
        }
        MapService mapService = SpringUtils.getBean(MapService.class);
        if (mapService.isInPosition(role, digTreasurePosition.getMapId(), digTreasurePosition.getX(), digTreasurePosition.getY(), 3) == false) {return false; }

        /**开始挖宝*/
        startDig(role);

        return true;
    }

    /**开始挖宝*/
    private void startDig(Role role) {
        role.setGatherType(Const.GATHER_TYPE_TREASURE);
        /**开始弹出挖宝进度条*/
        int currtime = new Long(new Date().getTime() / 1000).intValue();
        int endtime = currtime + 3;
        /**减1秒是因为会出现收到挖宝结束包在endtime之前*/
        role.pushTempCache("dig_treasure_end_time", endtime-1);
        RespStartGather respStartGather = new RespStartGather();
        respStartGather.setStartTime(currtime);
        respStartGather.setEndTime(endtime);
        respStartGather.setMsg("挖宝中…");
        respStartGather.setGather_style("default");
        MessagePusher.pushMessage(role, respStartGather);
        Pos pos = role.getActivity().getDigTreasurePosition();
        log.info("[TREASURE_TASK]|startDig|{}|{}|{}|{}|{}", role.getActivity().getDigTreasureType(), role.getUid(), pos.getMapId(), pos.getX(), pos.getY());
    }

    /**结束挖宝*/
    public void endDig(Role role) {
        role.popTempCache("dig_treasure_end_time");
        if (role.getGatherType() != Const.GATHER_TYPE_TREASURE) {
            return ;
        }

        TaskSet taskSet = getTaskSetByType(role);
        if (taskService.isTaskAccepted(role, taskSet) == false) {
            log.info("[TREASURE_TASK]|endDig|{}|{}|{}|{}", role.getActivity().getDigTreasureType(), role.getUid(), (taskSet != null ? taskSet.getId() : 0), "TaskNotAccept");
            return;
        }

        int endtime = role.getTempCache("dig_treasure_end_time", 0);
        if ((System.currentTimeMillis() / TimeUtil.ONE_SECOND) < endtime) {
            log.info("[TREASURE_TASK]|endDig|{}|{}|{}|{}", role.getActivity().getDigTreasureType(), role.getUid(), taskSet.getId(), endtime);
            return;
        }
        if (!SpringUtils.getBean(BagService.class).checkBagEnough(role, false, 1)) {
            MessagePusher.notify2Player(role, I18nId.PMT_412);
            return ;
        }
        if (!SpringUtils.getPetService().checkPetPosEnouth(role, 1)) {
            MessagePusher.notify2Player(role, I18nId.PMT_413);
            return ;
        }
        role.popTempCache("dig_treasure_end_time");

        /**重置任务*/
        doResetTask(role, taskSet);
        doAfterReset(role, taskSet);

        /**给奖励*/
        byte digTreasureType = role.getActivity().getDigTreasureType();
        giveReward(role, digTreasureType);

        /**没有挖出妖王时*/
        if (role.popTempCache("break_seal") == null) {
            /**还有藏宝图时显示是否继续使用*/
            checkContinueUseTreasureMapItem(role, digTreasureType);

        }

    }

    /**给奖励*/
    private void giveReward(Role role, byte digTreasureType) {
        log.info("[TREASURE_TASK]|giveReward|{}|{}|{}|{}", role.getActivity().getDigTreasureType(), role.getUid());
        if (digTreasureType == Const.DIG_TREASURE_TYPE_SUPER) {
            /**超级藏宝图奖励*/
            giveSuperTreasureReward(role);
        } else if (digTreasureType == Const.DIG_TREASURE_TYPE_NORMAL){
            /**普通藏宝图奖励*/
            giveNormalTreasureReward(role);
        } else if (digTreasureType == Const.DIG_TREASURE_TYPE_SUPER_SENIOR) {
            /**特级藏宝图奖励*/
            giveSuperSeniorTreasureReward(role);
        }
    }

    /**给特级藏宝图奖励*/
    private void giveSuperSeniorTreasureReward(Role role) {
        EquipService equipService = SpringUtils.getEquipService();
        String result = getRandom(wabaoDiaoLuoSenior);
        if ("money".equals(result)) {
            int money = Integer.parseInt(getRandom(tejiwabaoMoney)) * 100*30;
            SpringUtils.getRoleService().addMoney(role, money);
        } else if ("shoushi".equals(result)) {
            int[] levels = {50, 60,70};
            int index = ThreadLocalRandom.current().nextInt(levels.length);
            RoleEquip roleEquip = equipService.getRandomJewelry(levels[index], role);
            if(roleEquip== null){
                return;
            }
            equipService.refreshRoleEquip(role,roleEquip);

            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你获得了一件#R" + roleEquip.getName() + "#n。"));
        } else if ("bianyi".equals(result)) {
            if (SpringUtils.getPetService().isEquippedFull(role)) {
                MessagePusher.pushMessage(role,new RespMsg("当前宠物包裹已满，请整理后再来吧。"));
                return;
            }
            PetService petService = SpringUtils.getBean(PetService.class);
            Set<String> set = petService.getBianyiList();
            ArrayList<String> arrayList = new ArrayList<>(set);
            int index = ThreadLocalRandom.current().nextInt(set.size());
            String name = arrayList.get(index);
            PetObject petObject = PetDataPool.getPetObject(name);
            Pet pet = petService.addPet(petObject, role, false);
            petService.loadPet(role, pet);
            RespSummonMountNotify respSummonMountNotify = new RespSummonMountNotify();
            respSummonMountNotify.setId(pet.getId());
            MessagePusher.pushMessage(role, respSummonMountNotify);

            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你获得了一只#Y" + petObject.getName() + "#n。"));
            MessagePusher.notifyNumor(I18nId.PMT_201, role.getName(), petObject.getName());

            /**特级藏宝图获得宠物时公告消息*/
            String content = I18nIdDataPool.getI18nContent(I18nId.PMT_202, role.getName(), Const.TREASURE_SUPER_SENIOR_ITEM_NAME, petObject.getName());
            SpringUtils.getChatService().sendAdnotice(content);
        } else if ("nvwashi".equals(result)) {
            short newPos = SpringUtils.getBean(BagService.class).getPos(role, false);
            if (newPos <= 0) {
                MessagePusher.pushMessage(role, new RespMsg("你的包裹已满，无法获得#R超级女娲石#n。"));
                return;
            }
            equipService.addMall("超级女娲石", true, role);
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你获得了一块#R" + "超级女娲石" + "#n。"));
            MessagePusher.notifyNumor(I18nId.PMT_201, role.getName(), "超级女娲石");
        } else if ("shanggu".equals(result)) {
            SpringUtils.getBean(ShangGuBossHandler.class).breakSeal(role);
        } else if ("wannian".equals(result)) {
            SpringUtils.getBean(WanNianBossHandler.class).breakSeal(role);
        } else if ("weijianding".equals(result)) {
            short pos = SpringUtils.getBean(BagService.class).getPos(role, false);
            if (pos <= 0) {
                return;
            }
            int level = role.getLevel() - role.getLevel() % 10;
            equipService.getNotIdentifyEquip(level, role, pos);
        }
    }

    /**给超级藏宝图奖励*/
    private void giveSuperTreasureReward(Role role) {
        EquipService equipService = SpringUtils.getEquipService();
        String result = getRandom(wabaoDiaoLuo);
        if ("money".equals(result)) {
            int money = Integer.parseInt(getRandom(wabaoMoney)) * 10*30;
            SpringUtils.getRoleService().addVoucher(role, money);
        } else if ("shoushi".equals(result)) {
            int[] levels = {20, 35};
            int index = ThreadLocalRandom.current().nextInt(levels.length);
            RoleEquip roleEquip = equipService.getRandomJewelry(levels[index], role);
            if(roleEquip== null){
                return;
            }
            equipService.refreshRoleEquip(role,roleEquip);

            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你获得了一件#R" + roleEquip.getName() + "#n。"));
        } else if ("bianyi".equals(result)) {
            if (SpringUtils.getPetService().isEquippedFull(role)) {
                MessagePusher.pushMessage(role,new RespMsg("当前宠物包裹已满，请整理后再来吧。"));
                return;
            }
            PetService petService = SpringUtils.getBean(PetService.class);
            Set<String> set = petService.getBianyiList();
            ArrayList<String> arrayList = new ArrayList<>(set);
            int index = ThreadLocalRandom.current().nextInt(set.size());
            String name = arrayList.get(index);
            PetObject petObject = PetDataPool.getPetObject(name);
            Pet pet = petService.addPet(petObject, role, false);
            petService.loadPet(role, pet);
            RespSummonMountNotify respSummonMountNotify = new RespSummonMountNotify();
            respSummonMountNotify.setId(pet.getId());
            MessagePusher.pushMessage(role, respSummonMountNotify);

            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你获得了一只#Y" + petObject.getName() + "#n。"));
            MessagePusher.notifyNumor(I18nId.PMT_201, role.getName(), petObject.getName());

            /**超级藏宝图获得宠物时公告消息*/
            String content = I18nIdDataPool.getI18nContent(I18nId.PMT_202, role.getName(), Const.TREASURE_SUPER_ITEM_NAME, petObject.getName());
            SpringUtils.getChatService().sendAdnotice(content);
        } else if ("nvwashi".equals(result)) {
            short newPos = SpringUtils.getBean(BagService.class).getPos(role, false);
            if (newPos <= 0) {
                MessagePusher.pushMessage(role, new RespMsg("你的包裹已满，无法获得#R超级女娲石#n。"));
                return;
            }
            equipService.addMall("超级女娲石", true, role);
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你获得了一块#R" + "超级女娲石" + "#n。"));
            MessagePusher.notifyNumor(I18nId.PMT_201, role.getName(),Const.TREASURE_SUPER_ITEM_NAME, "超级女娲石");
        } else if ("shanggu".equals(result)) {
            SpringUtils.getBean(ShangGuBossHandler.class).breakSeal(role);
        } else if ("wannian".equals(result)) {
            SpringUtils.getBean(WanNianBossHandler.class).breakSeal(role);
        } else if ("weijianding".equals(result)) {
            short pos = SpringUtils.getBean(BagService.class).getPos(role, false);
            if (pos <= 0) {
                return;
            }
            int level = role.getLevel() - role.getLevel() % 10;
            equipService.getNotIdentifyEquip(level, role, pos);
        }
    }

    /**给普通藏宝图奖励*/
    private void giveNormalTreasureReward(Role role) {
        // 只出游戏币10000-100000
        int money = Integer.parseInt(getRandom(wabaoMoneyNormal)) * 10000;
        SpringUtils.getRoleService().addMoney(role, money);
    }

    public String getRandom(String wabaoMoney) {
        String[] strings1 = wabaoMoney.split(",");
        int total = 0;
        for (String ss : strings1) {
            String[] strings = ss.split("=");
            total += Integer.parseInt(strings[1]);
        }
        int result = ThreadLocalRandom.current().nextInt(total) + 1;
        int temp = 0;
        for (String ss : strings1) {
            String[] strings = ss.split("=");
            temp += Integer.parseInt(strings[1]);
            if (result <= temp) {
                return strings[0];
            }
        }
        return null;
    }

    /**检测有藏宝图道具时弹出是否继续使用*/
    public void checkContinueUseTreasureMapItem(Role role, byte digTreasureType) {
        digTreasureType = role.getActivity().getDigTreasureType();
        int remainCount = 0;
        String notifyType = null;
        EquipService equipService = SpringUtils.getEquipService();
        if (digTreasureType == Const.DIG_TREASURE_TYPE_SUPER) {
            remainCount = equipService.getCount(Const.TREASURE_SUPER_ITEM_NAME, true, role);
            notifyType = "chaoji_goon";
        } else if (digTreasureType == Const.DIG_TREASURE_TYPE_NORMAL){
            remainCount = equipService.getCount(Const.TREASURE_NORMAL_ITEM_NAME, true, role);
            notifyType = "normal_goon";
        } else if (digTreasureType == Const.DIG_TREASURE_TYPE_SUPER_SENIOR){
            remainCount = equipService.getCount(Const.TREASURE_SUPER_SENIOR_ITEM_NAME, true, role);
            notifyType = "teji_goon";
        }
        if (remainCount > 0) {
//            RespGeneralNotify respGeneralNotify = new RespGeneralNotify();
//            respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_BAOZANG_READY_SEARCH);//藏宝图
//            respGeneralNotify.setValue(notifyType);
//            MessagePusher.pushMessage(role, respGeneralNotify);

            AutoCangBaoTu autoCangBaoTu = new AutoCangBaoTu();
            autoCangBaoTu.setPara(notifyType);
            autoCangBaoTu.setTips("是否在次使用藏宝图？");
            autoCangBaoTu.setHasSgyw((byte)0);
            MessagePusher.pushMessage(role, autoCangBaoTu);
        }
    }

    public void delTask(Role role) {
        TaskSet taskSet = taskService.getTaskSet(DIG_TREASURE_TASKID_SUPER, role);
        /**任务已经接取时，删除原任务再添加一个*/
        if (taskService.isTaskAccepted(role, taskSet)) {
            giveUpTask(role, taskSet);
        }
    }
    public void delTask1(Role role) {
        TaskSet taskSet = taskService.getTaskSet(DIG_TREASURE_TASKID_NORMAL, role);
        /**任务已经接取时，删除原任务再添加一个*/
        if (taskService.isTaskAccepted(role, taskSet)) {
            giveUpTask(role, taskSet);
        }
    }
    public void delTask2(Role role) {
        TaskSet taskSet = taskService.getTaskSet(DIG_TREASURE_TASKID_SUPER_SENIOR, role);
        /**任务已经接取时，删除原任务再添加一个*/
        if (taskService.isTaskAccepted(role, taskSet)) {
            giveUpTask(role, taskSet);
        }
    }
}
